/*  Make the necessary includes and set up the variables.  */

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
    int sockfd;
    int len;
    struct sockaddr_in address;
    int result;
    char ch = (char)getpid();
	char send_buff[1024] = {0};
	int flag, size;
	int tcp_size;
	char *buf;

	printf("pid. = %d\n", (int)getpid());

/*  Create a socket for the client.  */

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
	
/*  Name the socket, as agreed with the server.  */

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(9752);
    len = sizeof(address);


/*  Now connect our socket to the server's socket.  */

    result = connect(sockfd, (struct sockaddr *)&address, len);

    if(result == -1) 
		if (EINPROGRESS != errno) {
			perror("oops: ");
			printf("%s\n", (char *)strerror(errno));
			exit(1);
		}

#if 1	
	flag = fcntl(sockfd, F_GETFL, 0);
	if (flag < 0) perror("F_GETFL error\n");
	flag = fcntl(sockfd, F_SETFL, flag|=O_NONBLOCK);
	if (flag < 0) perror("F_SETFL error\n");
#endif

	if (getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &flag, &size));
	printf("SO_RCVBUF is %d\n", flag);
	if (getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &flag, &size));
	printf("SO_SNDBUF is %d\n", flag);
	tcp_size = flag;


	printf("conn ok. fd is %d.\n", result);

/*  We can now read/write via sockfd.  */

//    result = write(sockfd, send_buff, 2);

	tcp_size *= 4;

	buf = malloc(tcp_size);
	if (!buf)
		perror("NO MEMORY!\n");

	fd_set rdfds;

	FD_ZERO(&rdfds);
	FD_SET(sockfd, &rdfds);

	while(1) {
#if 1
		printf("select waiting ... \n");
		select(sockfd + 1, (fd_set *)0, &rdfds, (fd_set *)0, (struct timeval *) 0);
 
		printf("slect Activity ... \n");

		if (FD_ISSET(sockfd, &rdfds)) {
#endif		
			printf("send bytes is %d ...... \n", tcp_size);
			write(sockfd, buf, 25);
//			result = write(sockfd, buf, tcp_size);
//			result = send(sockfd, buf, tcp_size, MSG_WAITALL);
//			result = send(sockfd, buf, tcp_size, MSG_DONTWAIT);
			printf("fd=%d, send server \"%d\"\n", sockfd, result);

			sleep(30);
		}

	}

    close(sockfd);
    exit(0);
}
